<template>
  <div>
    <a-drawer
      :open="props.open"
      title="详情"
      placement="right"
      @close="handleClose"
      width="400px"
    >
      <a-form :label-col="labelCol" :disabled="isForm" :model="formSate">
        <a-form-item label="子公司">
          <a-input
            style="width: 200px"
            disabled
            v-model:value="formSate.comNameLevel5"
          />
        </a-form-item>
        <a-form-item label="热源站">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.heatSourceName"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.heatSourceName"
          />
        </a-form-item>
        <a-form-item label="热源站名称(财产)">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.heatSourceNameACC"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.heatSourceNameACC"
          />
        </a-form-item>
        <a-form-item label="投产时间">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.createdTime"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-date-picker
            v-model:value="formSate.createdTime"
            placeholder="请选择投产时间"
            style="width: 200px"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="经度">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.longitude"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input v-model:value="formSate.longitude" style="width: 200px" />
        </a-form-item>
        <a-form-item label="纬度">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.latitude"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input v-model:value="formSate.latitude" style="width: 80px" />
          <a-button type="primary" :icon="h(EnvironmentOutlined)" @click="onGps"
            >获取经纬度</a-button
          >
        </a-form-item>
        <a-form-item label="热源的建设性质">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.heatSourceBelong"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.heatSourceBelong"
            style="width: 200px"
          >
            <a-select-option value="居民供热">居民供热</a-select-option>
            <a-select-option value="公建">公建</a-select-option>
            <a-select-option value="民建">民建</a-select-option>
            <a-select-option value="自有">自有</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="供热模式">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.heatingMode"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.heatingMode"
            style="width: 200px"
          >
            <a-select-option value="地暖">地暖</a-select-option>
            <a-select-option value="散热器">散热器</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否完成">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.isCompleted"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.isCompleted"
            style="width: 200px"
          >
            <a-select-option :value="1">完成</a-select-option>
            <a-select-option :value="0">未完成</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <div class="text-right">
        <a-button
          type="primary"
          :icon="h(ScheduleFilled)"
          @click="handleChangeRecord"
          >热源信息修改记录</a-button
        >
      </div>
      <template #footer v-if="isForm">
        <a-space>
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = true;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >修改</a-button
          >
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = false;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >批量修改</a-button
          >
        </a-space>
      </template>
      <template #footer v-if="!isForm">
        <a-space>
          <a-button type="primary" @click="onsubmit">提交</a-button>
          <a-button
            @click="
              () => {
                isForm = true;
                handleClose();
              }
            "
            >取消</a-button
          >
        </a-space>
      </template>
      <a-modal
        v-model:open="Map"
        title="选取经纬度"
        :footer="null"
        width="800px"
      >
        <AMapPicker
          :initial-longitude="formSate.longitude"
          :initial-latitude="formSate.latitude"
          @confirm="handleConfirmLocation"
        />
      </a-modal>
      <a-modal
        :visible="changeRecord"
        title="修改记录"
        :footer="null"
        width="1200px"
        @cancel="changeRecord = false"
      >
        <a-table
          :columns="columns"
          :data-source="changeRecordData"
          :pagination="pagination"
        />
      </a-modal>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
import { h, ref, reactive, onMounted, watch } from 'vue';
import {
  EditFilled,
  ScheduleFilled,
  EnvironmentOutlined,
} from '@ant-design/icons-vue';
// import AMapPicker from '#/components/Map/AMapPicker.vue';
import {
  updateHeatSource,
  getHeatSourceBatchOperation_four,
  getHeatSourceChangeRecordApi,
} from '#/api';
import { message } from 'ant-design-vue';

interface Props {
  selectedType: string;
  data: any;
  open: boolean;
  auth: Record<string, any>;
}

const props = defineProps<Props>();
const formSate = ref<Record<string, any>>({});
const changeRecordData = ref<any[]>([]);
watch(
  () => props.data,
  (newVal) => {
    console.log('newVal', newVal);
    // 确保newVal是一个数组，并且长度大于0，然后将其赋值给formSate.value
    if (newVal) {
      formSate.value = { ...newVal };
    }
  },
);
const changeRecord = ref(false);
const isEdit = ref(false);
const isForm = ref(true);
const Map = ref(false);
const labelCol = { style: { width: '120px' } };
const emit = defineEmits(['handleClose', 'refreshData']);
const handleClose = () => {
  emit('handleClose');
};
const columns = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    key: 'comNameLevel5',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    key: 'heatSourceName',
  },
  {
    title: '热源站名称(财务)',
    dataIndex: 'heatSourceNameACC',
    key: 'heatSourceNameACC',
  },
  {
    title: '投产时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    key: 'longitude',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    key: 'latitude',
  },
  {
    title: '热源的建设性质',
    dataIndex: 'heatSourceBelong',
    key: 'heatSourceBelong',
  },
  {
    title: '供热模式',
    dataIndex: 'heatingMode',
    key: 'heatingMode',
  },
  {
    title: '是否完成',
    dataIndex: 'isCompleted',
    key: 'isCompleted',
  },
  {
    title: '操作类型',
    dataIndex: 'operType',
    key: 'operType',
  },
  {
    title: '操作人',
    dataIndex: 'reporter',
    key: 'reporter',
  },
  {
    title: '操作时间',
    dataIndex: 'operTime',
    key: 'operTime',
  },
];
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    getHeatSourceChangeRecordApi({
      page: page,
      limit: pageSize,
      heatSourceID: (props.data as any).heatSourceId,
    }).then((res) => {
      // console.log('res', res);
      changeRecordData.value = res.data.data;
      pagination.total = res.data.count;
    });
  },
});
// 用于存储批量编辑时选中的字段
const selectedFields = reactive({
  comNameLevel5: false,
  heatSourceName: false,
  heatSourceNameACC: false,
  createdTime: false,
  longitude: false,
  latitude: false,
  heatSourceBelong: false,
  heatingMode: false,
  isCompleted: false,
});

// 重置选中的字段
const resetSelectedFields = () => {
  Object.keys(selectedFields).forEach((key) => {
    selectedFields[key] = false;
  });
};

// 打开地图选择器
const onGps = () => {
  Map.value = true;
};

// 处理地图选择器确认事件
const handleConfirmLocation = (location: {
  longitude: number;
  latitude: number;
}) => {
  console.log('location', location);
  formSate.value.longitude = location.longitude.toString();
  formSate.value.latitude = location.latitude.toString();
  Map.value = false;
};
const onsubmit = () => {
  if (isEdit.value) {
    // 单独修改逻辑
    const data = {
      ...formSate.value,
      regionId: (props.data as any).regionId,
      applicationReason: (props.data as any).applicationReason,
      attachmentLocation: (props.data as any).attachmentLocation,
      operateObject: (props.data as any).operateObject,
    };
    updateHeatSource(data).then((res) => {
      console.log('单独修改', res);
      if (res === '修改成功!') {
        message.success(res);
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res || '修改失败!');
      }
    });
  } else {
    // 批量修改逻辑
    // 创建一个只包含选中字段的对象
    const selectedData = {};
    Object.keys(selectedFields).forEach((key) => {
      if (selectedFields[key]) {
        selectedData[key] = formSate.value[key];
      }
    });

    // 检查是否有选中的字段
    if (Object.keys(selectedData).length === 0) {
      message.warning('请至少选择一个要修改的字段');
      return;
    }

    // 这里需要实现批量修改的API调用
    console.log('批量修改的数据', selectedData);
    const data = {
      ...selectedData,
      regionId: (props.data as any).regionId,
      applicationReason: (props.data as any).applicationReason,
      attachmentLocation: (props.data as any).attachmentLocation,
      operateObject: (props.data as any).operateObject,
    };
    // 示例：调用批量修改API
    getHeatSourceBatchOperation_four(data).then((res) => {
      if (res.data.code === 200) {
        message.success('批量修改成功!');
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res.message || '批量修改失败!');
      }
    });

    // 临时提示，实际项目中应替换为真实API调用
    // message.success('批量修改功能已触发，请实现对应的API');
    // isForm.value = true;
    // handleClose();
  }
};
const handleChangeRecord = () => {
  changeRecord.value = true;
  getHeatSourceChangeRecordApi({
    page: pagination.current,
    limit: pagination.pageSize,
    heatSourceID: (props.data as any).heatSourceId,
  }).then((res) => {
    // console.log('res', res);
    changeRecordData.value = res.data.data;
    pagination.total = res.data.count;
  });
};
</script>
<style scoped>
.mr-2 {
  margin-right: 8px;
}
</style>
